package com.ygqh.baby.service.wechat.api;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.api.UserApi;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.ygqh.baby.service.wechat.model.Following;

public class YgUserApi extends UserApi {
	private final TokenHolder ygTokenHolder;

	public YgUserApi(TokenHolder tokenHolder) {
		super(tokenHolder);
		this.ygTokenHolder = tokenHolder;
	}

	/**
	 * 获取公众号一定数量(10000)的关注者列表
	 * 
	 * @param nextOpenId
	 *            下一次拉取数据的openid 不填写则默认从头开始拉取
	 * @return 关注者信息 <font color="red">不包含用户的详细信息</font>
	 * @throws WeixinException
	 * @see <a href=
	 *      "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840&token=&lang=zh_CN">
	 *      获取关注者列表</a>
	 * @see com.foxinmy.weixin4j.mp.model.Following
	 */
	public Following getFollowingOpenIds(String nextOpenId) throws WeixinException {
		String following_uri = getRequestUri("following_uri");
		Token token = ygTokenHolder.getToken();
		WeixinResponse response = weixinExecutor.get(String.format(following_uri, token.getAccessToken(), nextOpenId == null ? "" : nextOpenId));

		JSONObject result = response.getAsJson();
		Following following = JSON.toJavaObject(result, Following.class);

		if (following.getCount() > 0) {
			following.setOpenIds(JSON.parseArray(result.getJSONObject("data").getString("openid"), String.class));
		}
		return following;
	}

	public List<String> getAllOpenIds() throws WeixinException {
		List<String> list = new ArrayList<String>();
		String nextOpenId = null;
		Following f = null;
		for (;;) {
			f = this.getFollowingOpenIds(nextOpenId);
			if (f.getCount() == 0) {
				break;
			}
			list.addAll(f.getOpenIds());
			nextOpenId = f.getNextOpenId();
		}
		return list;
	}
}
